package com.ffalcon.mercury.android.sdk.demo;

import android.app.Dialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.PlayerView;

public class CustomDialog extends Dialog {

    private Context context;
    private String text;
    private String imageUrl;
    private String videoUrl;
    private LinearLayout contentLayout;
    private ExoPlayer player;
    private PlayerView playerView;


    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable autoDismissRunnable;


    public CustomDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    public CustomDialog setText(String text) {
        this.text = text;
        return this;
    }

    public CustomDialog setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
        return this;
    }

    public CustomDialog setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_dialog_layout);

        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.TOP | Gravity.END;
            window.setAttributes(params);
        }

        contentLayout = findViewById(R.id.contentLayout);
        playerView = ((PlayerView) findViewById(R.id.playerView));
        if (text != null && !text.isEmpty()) {
            showText();
        } else if (imageUrl != null && !imageUrl.isEmpty()) {
            showImage();
        } else if (videoUrl != null && !videoUrl.isEmpty()) {
            showVideo();
        }
    }

    private void showText() {
        TextView textView = new TextView(context);
        textView.setText(text);
        textView.setPadding(16, 16, 16, 16);
        contentLayout.addView(textView);

        setupAutoDismiss();
    }

    private void showImage() {
        ImageView imageView = new ImageView(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               400, // 宽度设置为100dp
                300  // 高度设置为100dp
        );
        imageView.setLayoutParams(params);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        contentLayout.addView(imageView);



        Glide.with(context)

                .load(imageUrl)

                .into(imageView);

        setupAutoDismiss();
    }
    private void showVideo() {
        // 显示播放器视图
        playerView.setVisibility(View.VISIBLE);

        // 创建ExoPlayer实例
        player = new ExoPlayer.Builder(context).build();
        playerView.setPlayer(player);

        // 设置媒体源
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(videoUrl));
        player.setMediaItem(mediaItem);

        // 准备并播放
        player.prepare();
        player.setPlayWhenReady(true);
        // 监听视频播放完成事件
        player.addListener(


        new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_ENDED) {
                    dismiss(); // 视频播放结束后关闭对话框
                }
            }
        });
    }

    private void setupAutoDismiss() {
        // 移除之前的回调（如果有）
        if (autoDismissRunnable != null) {
            handler.removeCallbacks(autoDismissRunnable);
        }

        // 设置5秒后执行关闭操作
        autoDismissRunnable = this::dismiss;
        handler.postDelayed(autoDismissRunnable, 5000); // 5000毫秒 = 5秒
    }

    // 管理播放器生命周期
    @Override
    public void onStart() {
        super.onStart();
        if (player == null && videoUrl != null) {
            showVideo();
        }
    }

    @Override
    public void dismiss() {
        // 移除所有回调，避免内存泄漏
        if (handler != null && autoDismissRunnable != null) {
            handler.removeCallbacks(autoDismissRunnable);
        }

        super.dismiss();
    }

    @Override
    public void onStop() {
        super.onStop();
        releasePlayer();

        // 移除回调
        if (handler != null && autoDismissRunnable != null) {
            handler.removeCallbacks(autoDismissRunnable);
        }
    }

    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
        }
    }

}